package com.dayatang.product.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import com.dayatang.domain.QuerySettings;


@Entity
@Table(name = "products")
public class Product extends MyAbstractEntity {

	private static final long serialVersionUID = 6223006207654563680L;

	private String name;
	
	@Temporal(TemporalType.DATE)
	@Column(name = "release_date")
	private Date releaseDate;
	
	@Column(name = "product_describe")
	private String productDescribe;
	
	@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "product", fetch=FetchType.EAGER)
	private Set<ProductTrial> productTrials = new HashSet<ProductTrial>();
	
	// 试用期
	@Column(name = "trial_period")
	private long trialPeriod;
	
	@NotNull
	@Column(name = "mark", nullable = false, unique = true)
	private String mark;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getReleaseDate() {
		return releaseDate;
	}

	public void setReleaseDate(Date releaseDate) {
		this.releaseDate = releaseDate;
	}

	public String getProductDescribe() {
		return productDescribe;
	}

	public void setProductDescribe(String productDescribe) {
		this.productDescribe = productDescribe;
	}

	public Set<ProductTrial> getProductTrials() {
		return new HashSet<ProductTrial>(productTrials);
	}

	public void addProductTrial(ProductTrial productTrial) {
		productTrial.setProduct(this);
		productTrials.add(productTrial);
	}
	
	public void removeProductTrial(ProductTrial productTrial) {
		productTrials.remove(productTrial);
	}
	
	public void setProductTrials(Set<ProductTrial> productTrials) {
		this.productTrials = productTrials;
	}

	public long getTrialPeriod() {
		return trialPeriod;
	}

	public void setTrialPeriod(long trialPeriod) {
		this.trialPeriod = trialPeriod;
	}

	public String getMark() {
		return mark;
	}

	public void setMark(String mark) {
		this.mark = mark;
	}
	
	public static Product getProductByRemark(String mark) {
		return getRepository().getSingleResult(QuerySettings.create(Product.class).eq("mark", mark));
	}

	public int hashCode() {
		return new HashCodeBuilder(17, 37).append(name).toHashCode();
	}

	public boolean equals(Object other) {
		if (!(other instanceof Product))
			return false;
		Product castOther = (Product) other;
		return new EqualsBuilder().append(name, castOther.name).append(releaseDate, castOther.releaseDate).isEquals();
	}

	public String toString() {
		return name;
	}

}
